package com.xuzimian.globaldemo.designpatterns.proxy.dynamic.performance;

import com.xuzimian.globaldemo.designpatterns.proxy.ISubject;

import java.util.function.Supplier;

import static java.lang.System.currentTimeMillis;
import static java.lang.System.out;

public class DynamicProxyPerformanceDemo {
    public static final int CIRCLE = 10000000;
    public static long begin = currentTimeMillis();

    public static void main(String[] args) throws Exception {

        executeProxyForTestPerformance("Jdk", ProxyFactory::createJdkProxy);

        executeProxyForTestPerformance("Cglib", ProxyFactory::createCglibProxy);

        executeProxyForTestPerformance("Javassist Dynamic", ProxyFactory::createJavassistDynProxy);

        executeProxyForTestPerformance("Javassist Bytecode", ProxyFactory::createJavassistBytecodeDynamicProxy);
    }


    private static void executeProxyForTestPerformance(String tag, Supplier<ISubject> createProxy) throws Exception {
        ISubject principal = createProxy.get();
        println("Create " + tag + " Proxy :" + principal.getClass().getName(), begin);
        resetBegin();
        for (int i = 0; i < CIRCLE; i++) {
            principal.processBusiness();
        }
        out.println("Call " + tag + " Proxy : " + (currentTimeMillis() - begin));
        resetBegin();
        out.println();
    }

    private static void println(String msg, long begin) {
        out.print(msg + " - " + (currentTimeMillis() - begin) + "ms");
    }

    private static void resetBegin() {
        begin = currentTimeMillis();
    }
}
